<template>
  <div class="checkin-container">
    <!-- 已打卡人数提示 -->
    <div class="checkin-count">
      今日已打卡人数：{{ checkedCount }}
    </div>

    <!-- 打卡按钮 -->
    <div
      class="checkin-circle"
      :class="{ 'morning-checked': hasMorning, 'afternoon-checked': hasAfternoon }"
      @click="handleCheckin"
      :disabled="isLoading || hasAfternoon"
    >
      <el-loading
        v-if="isLoading"
        type="circle"
        color="#fff"
        size="30px"
      ></el-loading>
      <span class="checkin-text" v-else>
        {{ getButtonText() }}
      </span>
    </div>

    <!-- 打卡状态提示 -->
    <div class="checkin-status">
      <span v-if="hasMorning">上午已打卡：{{ morningTime }}</span>
      <span v-if="hasAfternoon">下午已打卡：{{ afternoonTime }}</span>
    </div>

    <!-- 打卡时间提示 -->
    <div class="checkin-time">
      <div>早上打卡时间：09:00</div>
      <div>下午打卡时间：18:00</div>
    </div>
  </div>
</template>

<script>
import { addAttendance, countChecked, getCurrentUserCheckin } from "@/api/system/attendance";
import { mapGetters } from "vuex";
import { mapState, mapActions } from "vuex"; // 引入Vuex辅助函数

export default {
  name: "CheckIn",
  computed: {
    // 获取当前用户ID
    ...mapGetters(["id"]),
    // 获取Vuex中存储的打卡时间
    ...mapState("attendance", {
      morningTime: state => state.morning,
      afternoonTime: state => state.afternoon
    }),
    // 判断是否完成上午/下午打卡
    hasMorning() {
      return !!this.morningTime;
    },
    hasAfternoon() {
      return !!this.afternoonTime;
    },
    // 今日日期（yyyy-MM-dd）
    today() {
      return new Date().toISOString().split('T')[0];
    }
  },
  data() {
    return {
      checkedCount: 0,
      isLoading: false
    };
  },
  created() {
    this.getCheckedCount();
    this.initCheckinStatus(); // 初始化已打卡状态（从数据库获取）
  },
  methods: {
    // 映射Vuex的actions
    ...mapActions("attendance", ["recordMorning", "recordAfternoon", "resetAttendance"]),

    // 按钮显示文本
    getButtonText() {
      if (this.hasAfternoon) {
        return "今日已完成";
      } else if (this.hasMorning) {
        return "下午打卡";
      } else {
        return "上午打卡";
      }
    },

    // 获取今日已打卡人数
    getCheckedCount() {
      countChecked({ checkDate: this.today }).then(response => {
        this.checkedCount = response.data;
      }).catch(err => {
        this.$message.error("获取打卡人数失败：" + (err.msg || err.message));
      });
    },

    // 初始化打卡状态（从数据库加载到Vuex）
    initCheckinStatus() {
      getCurrentUserCheckin({
        userId: this.id,
        checkDate: this.today
      }).then(response => {
        const data = response.data || {};
        // 如果数据库已有打卡记录，同步到Vuex
        if (data.morning) {
          this.recordMorning(data.morning);
        }
        if (data.afternoon) {
          this.recordAfternoon(data.afternoon);
        }
      }).catch(err => {
        console.log("初始化打卡状态失败：", err);
      });
    },

    // 处理打卡逻辑（两次打卡完成后提交数据库）
    handleCheckin() {
      if (this.isLoading || this.hasAfternoon) return;

      this.isLoading = true;
      // 获取当前时间（HH:mm:ss）
      const now = new Date();
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      const currentTime = `${hours}:${minutes}:${seconds}`;

      if (!this.hasMorning) {
        // 第一次打卡：记录上午时间到Vuex
        this.recordMorning(currentTime);
        this.$message.success("上午打卡成功！");
        this.isLoading = false;
      } else {
        // 第二次打卡：记录下午时间到Vuex，然后提交数据库
        this.recordAfternoon(currentTime);
        this.$message.success("下午打卡成功！正在同步数据...");

        // 构造完整打卡数据（两次打卡都完成后提交）
        const checkinData = {
          userId: this.id,
          checkDate: this.today,
          morning: this.morningTime, // 从Vuex获取上午时间
          afternoon: this.afternoonTime // 从Vuex获取下午时间
        };

        // 提交到数据库
        addAttendance(checkinData).then(() => {
          this.$message.success("今日打卡已完成！");
          this.getCheckedCount(); // 刷新打卡人数
        }).catch(err => {
          this.$message.error("数据同步失败：" + (err.msg || err.message));
          // 同步失败时回滚下午打卡状态
          this.recordAfternoon(null);
        }).finally(() => {
          this.isLoading = false;
        });
      }
    }
  }
};
</script>

<style scoped>
/* 样式与之前保持一致 */
.checkin-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  padding: 20px;
}

.checkin-count {
  font-size: 16px;
  color: #666;
  margin-bottom: 15px;
  font-weight: 500;
}

.checkin-circle {
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background-color: #1890ff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
  margin: 20px 0;
  position: relative;
}

.checkin-circle.morning-checked {
  background-color: #40a9ff;
  box-shadow: 0 4px 12px rgba(64, 169, 255, 0.3);
}

.checkin-circle.afternoon-checked {
  background-color: #52c41a;
  box-shadow: 0 4px 12px rgba(82, 196, 26, 0.3);
}

.checkin-text {
  color: white;
  font-size: 28px;
  font-weight: bold;
}

.checkin-status {
  font-size: 14px;
  color: #333;
  margin-bottom: 15px;
  text-align: center;
  line-height: 1.5;
}

.checkin-time {
  text-align: center;
  color: #666;
  font-size: 14px;
  line-height: 1.8;
}

::v-deep .el-loading-spinner {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
